LONG Psemaphore( WORD mode, LONG id, LONG timeout );
For example, a semaphore may be used to protect access to data structures which are in shared memory and which are used by multiple threads in a process: before using the memory a thread must gain ownership of the guarding semaphore, and when finished the thread must release the semaphore. The semaphore would be created during initialization and destroyed during shutdown.
Semaphores are identified by an id, which is an arbitrary longword. This is the semaphore's "name." The id used to create the semaphore is the "name" of that semaphore from then on. When using semaphores, you should strive to use a longword that is unique. Using four ASCII characters which spell out something is common: 0x4b4f444f ("MODM") for instance might be the id of a semaphore that controls access to a modem. (Actually, this would be a poor choice, since there can be more than one modem in a system and this semaphore ID isn't flexible enough to handle that. "MDM1" might be better.)
Semaphore id's beginning with 0x5f (the underscore character) are reserved for operating system use.
The timeout argument is only used in Mode 2. It is ignored in other modes. A timeout of zero means "return immediately." A value of -1 means "forever" - that is, never time out. Other values are a number of milliseconds to wait for the semaphore before timing out.
The mode argument is used to tell what operation the caller desires:
When a process terminates, any semaphores it owns are released.
At most one process may own a semaphore. Ownership is not inherited by children (fork()) or across exec().
Once created, semaphores are never destroyed except upon request. Thus if a program creates a semaphore and then crashes the semaphore will never go away.
Semaphores can be implemented using named pipes and file locking. Technically, then, semaphores are redundant. The facility is included as a kernel call because it was deemed necessary to have this kind of exclusion available with little persistent state or system-call overhead.